<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jsonp初步封装</title>
</head>
<body>
    <script>
        // url封装
        function formate(url,dataObj){
            var start = true;
            var type = "GET";
            if(typeof url === 'object' && !(url instanceof Array)){
                dataObj = url;
                url = '';
                type = "POST";
            }

            // 2.参数拼接
            for(var key in dataObj){
                // get请求
                if(type === "GET"){
                    url += (start?"?":"&")+key+"="+dataObj[key];
                // post请求
                }else{
                    url += (start?"":"&")+key+"="+dataObj[key];
                }
                start = false;
            }
            return url;
        }

        // jsonp的ajax封装
        function ajax(method,url,_callback,dataObj){

            // 设置默认函数名：有定义函数名时则使用函数名，没有则使用默认函数名callback
            dataObj.jsonpcallback = dataObj.jsonpcallback ? dataObj.jsonpcallback : "callback";

            // 请求发送
            var script = document.createElement("script");
            script.src = formate(url,dataObj);
            document.body.appendChild(script);

            // 响应处理：同为window的callback函数，内部添加_以示区分
            window[dataObj.jsonpcallback] = data =>{
                _callback(data);
            }

            // 删除请求
            script.remove();
        }

        ajax("jsonp","https://api.gogoup.com/p1/data/recommend",function(data){
            console.log(data);
        },{
            type:0,     
            pageNo:2, 
            pageSize:5, 
            fromId:379, 
            jsonpcallback:'other',
            _:Date.now()
        });

    </script>
</body>
</html>